package com.lihaozhe.handler;

import com.lihaozhe.util.response.ResponseResult;
import com.lihaozhe.util.result.ResultCode;
import com.lihaozhe.util.servlet.BaseServlet;
import com.lihaozhe.util.string.StringUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李昊哲
 * @version 1.0
 * 2021/11/28 16:16
 */
@Component
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        ResponseResult<String> result = new ResponseResult<>();
        if (!StringUtil.isBlank(exception.getMessage())) {
            result.setCode(ResultCode.CODE_ERROR.getCode());
            result.setMsg(ResultCode.UNAUTHORIZED.getMsg());
            result.setData(exception.getMessage());
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        BaseServlet.printJsonObject(response,result);
    }
}
